"""
用户管理
"""
from django.shortcuts import render, redirect, HttpResponse
from rbac import models
from django.urls import reverse
from rbac.forms.user import UserModelForm,UpdateModelForm,ConfirmpasswordModelForm



def user_list(request):
    """
    角色列表
    :param request:
    :return:
    """
    role_queryset = models.UserInfo.objects.all().values()
    return render(request, 'rbac/user_list.html', {'role': role_queryset})


def user_add(request):
    """
    添加角色
    :param request:
    :return:
    """
    if request.method == "GET":
        form = UserModelForm()
        return render(request, 'rbac/role_add.html', {'form': form})
    form = UserModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect(reverse('rbac:user_list'))
    return render(request, 'rbac/role_add.html', {'form': form})


def user_edit(request, pk):
    obj = models.UserInfo.objects.filter(id=pk).first()
    if not obj:
        return HttpResponse('用户不存在')
    if request.method == "GET":
        form = UpdateModelForm(instance=obj)  # instance默认值
        return render(request, 'rbac/role_add.html', {'form': form})
    form = UpdateModelForm(instance=obj, data=request.POST)
    if form.is_valid():
        form.save()
        return redirect(reverse('rbac:user_list'))


def user_del(request, pk):
    origin_url = reverse('rbac:user_list')  # 取消按钮
    if request.method == "GET":
        return render(request, 'rbac/delete.html', {'cancel': origin_url})
    models.UserInfo.objects.filter(id=pk).delete()
    return redirect(origin_url)



def user_reset_pwd(request,pk):
    """
    重置密码
    :param request:
    :return:
    """

    obj = models.UserInfo.objects.filter(id=pk).first()
    if not obj:
        return HttpResponse('用户不存在')
    if request.method == "GET":
        form = ConfirmpasswordModelForm()
        return render(request, 'rbac/role_add.html', {'form': form})
    form = ConfirmpasswordModelForm(instance=obj, data=request.POST)
    if form.is_valid():
        form.save()
        return redirect(reverse('rbac:user_list'))
    return render(request, 'rbac/role_add.html', {'form': form})




